import 'dart:async';
import 'dart:io';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/manager/audit_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/bean/ywx_count.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/manager/user_manager.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';

import '../bean/works_2023/purcontract_bean.dart';
import '../bean/worksdo/material_requisition_bean.dart';

///审核数据
class ReviewModel {
  ///获取审核列表数据
  ///ReviewType 审核类型
  ///PageNo 页码,从0开始。
  ///PageSize 每页显示条目数量
  ///searchInfo 搜索条件
  static Future<AppHttpResult<List<ContractCopyInfo>, ContractCopyInfo>>
      getContractdogetlist(BuildContext context, bool isEnableLoad,
          {String? ReviewType,
          String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer = new Completer<
        AppHttpResult<List<ContractCopyInfo>, ContractCopyInfo>>();
    var url = Url.baseurl() + Url.contractdogetlist;
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    var subData = SubData();
    subData.commondata = CommonData();
    subData.ReviewType = ReviewType;
    subData.PageNo = PageNo;
    subData.PageSize = PageSize!;
    subData.InsertStartDatetime = searchInfo?.InsertStartDatetime; //开始时间
    subData.InsertEndDatetime = searchInfo?.InsertEndDatetime; //结束时间
    //subData.businessdata = searchInfo?.getContractCopyInfo();//搜索条件
    subData.businessdata = searchInfo; //fixme 搜索条件
    if (searchInfo?.item?.changerecord ?? false) {
      ///fixme 提成比例审核，更改记录标志
      subData.History = "true";
    } else {
      subData.History = "false";
    }
    var queryParameters = Map<String, dynamic>();
    var data = subData.jsonEncodeToJson();
    queryParameters['data'] = data;
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('列表提交数据：${data}');
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //print('待审核列表数据:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<ContractCopyInfo>, ContractCopyInfo>>(
              AppHttpResult()
                ..Data = <ContractCopyInfo>[]
                ..t2 = ContractCopyInfo())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<ContractCopyInfo>, ContractCopyInfo>>;
  }

  ///获取审核列表数据(详情)
  static Future<AppHttpResult<String, String>> getContractapplygetinfo(
    BuildContext context,
    bool isEnableLoad, {
    bool History = false,
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.contractapplygetinfo;
    var token = AppDataConfig.getToken();
    var subData = SubData();
    subData.commondata = CommonData();
    subData.ReviewType =
        AuditManager.getAuditManager().item!.ReviewType!; //审核类型
    subData.businessdata = AuditManager.getAuditManager().ReviewTypeId; //审核类型ID
    subData.BodyId = AuditManager.getAuditManager().BodyId; //采购合同审核详细需要。
    if (History) {
      subData.History = History?.toString(); //是否获取历史数据
    } else {
      subData.History = "false";
    }
    subData.IsApproval = AuditManager.getAuditManager().IsApproval.toString();
    var queryParameters = Map<String, dynamic>();
    queryParameters['data'] = subData.jsonEncodeToJson();
    // if(!History){
    //   print('详情提交参数：${ subData.jsonEncodeToJson()}');
    // }
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    var isEnableLog = AppDataConfig.isEnableLog;
    // if(!History){
    //   isEnableLog=true;
    // }
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (!History) {
          if (onError != null) {
            onError?.call(code, error);
          } else {
            AppDialog.showDialogWithError(context, code, error);
          }
        }
      })
      ..onSuccess((result) {
        // if (!History) {
        //   print('审核详情数据:\n$result');
        // }
        //print("数据总长度：${result?.length}");
        // PrintUtils.printlnLong('返回数据:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..isAllowedRepeat = true
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..connectTimeout = 0 //fixme 0没有时间限制;防止数据量过大超时。
      ..contentType = ContentType.form
      ..isEnableLog = isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  ///获取合同审核信息(提成比例审核里的合同信息)
  ///ContractCode 合同编号
  ///ContractId 合同编号ID
  static Future<AppHttpResult<String, String>> getContractapplygetinfo2(
    BuildContext context,
    String ContractCode,
    String ContractId,
    bool isEnableLoad, {
    bool History = false,
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.getContractInfo;
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.ReviewType =
    // AuditManager.getAuditManager().item!.ReviewType!; //审核类型
    // subData.businessdata = AuditManager.getAuditManager().ReviewTypeId; //审核类型ID
    // if (History) {
    //   subData.History = History?.toString(); //是否获取历史数据
    // } else {
    //   subData.History = "false";
    // }
    // subData.IsApproval = AuditManager.getAuditManager().IsApproval.toString();
    var queryParameters = Map<String, dynamic>();
    //queryParameters['data'] = subData.jsonEncodeToJson();
    ContractParams params = ContractParams();
    params.ContractCode = ContractCode; //合同编号
    params.ContractId = ContractId; //合同编号id
    queryParameters['data'] = params.jsonEncodeToJson();
    // if(!History){
    //   print('详情提交参数：${ subData.jsonEncodeToJson()}');
    // }
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    var isEnableLog = AppDataConfig.isEnableLog;
    // if(!History){
    //   isEnableLog=true;
    // }
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (!History) {
          if (onError != null) {
            onError?.call(code, error);
          } else {
            AppDialog.showDialogWithError(context, code, error);
          }
        }
      })
      ..onSuccess((result) {
        // if (!History) {
        //   print('合同信息:\n$result');
        // }
        //print("数据总长度：${result?.length}");
        // PrintUtils.printlnLong('返回数据:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..isAllowedRepeat = true
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..connectTimeout = 0 //fixme 0没有时间限制;防止数据量过大超时。
      ..contentType = ContentType.form
      ..isEnableLog = isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  ///获取审核列表数据(详情)；采购合同审核，历史合同
  ///PurContractCode 采购合同号
  static Future<AppHttpResult<List<PurContractBean>, PurContractBean>>
      getContractapplygetinfoHistory(BuildContext context, bool isEnableLoad,
          {ResponseCallbackWithStringCode_? onError = null,
          String? ReviewType,
          String? PageNo,
          String? PageSize = "15",
          String? PurContractCode = "",
          SearchInfo? searchInfo}) async {
    Completer completer =
        new Completer<AppHttpResult<List<PurContractBean>, PurContractBean>>();
    var url = Url.baseurl() + Url.GetPurContractBodyInfo;
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    var subData = SubData();
    subData.commondata = CommonData();
    subData.ReviewType = ReviewType;
    subData.PageNo = PageNo;
    subData.PageSize = PageSize!;
    subData.InsertStartDatetime = searchInfo?.InsertStartDatetime; //开始时间
    subData.InsertEndDatetime = searchInfo?.InsertEndDatetime; //结束时间
    searchInfo?.PurContractCode = PurContractCode; //fixme 采购合同号
    //subData.businessdata = searchInfo?.getContractCopyInfo();//搜索条件
    subData.businessdata = searchInfo; //fixme 搜索条件
    var queryParameters = Map<String, dynamic>();
    var data = subData.jsonEncodeToJson();
    queryParameters['data'] = data;
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('列表提交数据：${data}');
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..onSuccess((result) {
        // print('采购单合同历史合同数据:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<PurContractBean>, PurContractBean>>(
              AppHttpResult()
                ..Data = <PurContractBean>[]
                ..t2 = PurContractBean())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<PurContractBean>, PurContractBean>>;
  }
}
